<?php
require '../model/topicDao.php';
if($_SERVER["REQUEST_METHOD"]=="POST"){
    $topicId = $_POST['topicId'];
    $userId = $_POST['userId'];
    
    // 检查用户是否已经点赞过该帖子
    $alreadyLiked = check_user_liked($topicId, $userId);
    
    if($alreadyLiked) {
        // 如果已经点赞过，则取消点赞
        $result = unlike_topic($topicId, $userId);
        if($result) {
            echo json_encode(["status" => "success", "action" => "unliked"]);
        } else {
            echo json_encode(["status" => "error", "message" => "取消点赞失败"]);
        }
    } else {
        // 如果没有点赞过，则添加点赞
        $addRecord = add_like_record($topicId, $userId);
        $result = like_topic($topicId);
        if($result && $addRecord) {
            echo json_encode(["status" => "success", "action" => "liked"]);
        } else {
            echo json_encode(["status" => "error", "message" => "点赞失败"]);
        }
    }
}else{
    header("location:../views/error.php?msg=非法访问");
}
?>